<?php
namespace haibao\erp\data\product;

use \haibao\frame\data\query\Condition;
use \haibao\erp\model\filter\product\ProductCategory as ProductCategoryFilter;
use \haibao\erp\model\data\product\ProductCategory as ProductCategoryModel;

class ProductCategory extends \haibao\erp\data\BaseMysql{
	
	private static $cacheCategoryDictName = 'CategroyDict';
	private static $cacheCategoryTreeName = 'CategoryTree';
	
	
	public function __construct(){
		parent::__construct('\haibao\erp\model\data\product\ProductCategory');
	}
	
	/**
	 * 获取分类树形结构
	 * @return array
	 */
	public function getCategoryTree(){
		$categoryTreeCache = $this->getCache(self::$cacheCategoryTreeName);
		return $categoryTreeCache ? unserialize($categoryTreeCache) : $this->setCategoryTree();
	}
	
	/**
	 * 设置分类树形
	 * @param $return Boolean 是否需要返回值
	 */
	private function setCategoryTree($return = true){
		$categoryTree = array();
		$categorysDict = $this->getAllCategorysDict();
        if($categorysDict){
            foreach($categorysDict as $categoryDict){
                if(isset($categorysDict[$categoryDict[ProductCategoryFilter::CONDITION_FIELD_NAME_PARENTID]])){
                    $categorysDict[$categoryDict[ProductCategoryFilter::CONDITION_FIELD_NAME_PARENTID]]['children'][] = &$categorysDict[$categoryDict[ProductCategoryFilter::CONDITION_FIELD_NAME_ID]];
                }else{
                    $categoryTree[$categoryDict[ProductCategoryFilter::CONDITION_FIELD_NAME_ID]] = &$categorysDict[$categoryDict[ProductCategoryFilter::CONDITION_FIELD_NAME_ID]];
                }
            }
        }
        $categoryTree && $this->setCache(self::$cacheCategoryTreeName, serialize($categoryTree));
		if($return){
			return $categoryTree;
		}
	}
	/**
	 * 获取没有父子关系的分类详情
	 */
	public function getAllCategorysDict(){
		$categorysDictCache = $this->getCache(self::$cacheCategoryDictName);
		return $categorysDictCache ? unserialize($categorysDictCache) : $this->setAllCategorysDict();
	}
	
	/**
	 * 将全部可用的产品分类放入缓存中
	 * @param $return Boolean 是否需要返回值
	 */
	private function setAllCategorysDict($return = true){
		$productCategoryFilter = new ProductCategoryFilter();
		
		$productCategoryFilter->order(ProductCategoryFilter::CONDITION_FIELD_NAEM_ORDERNO);
		$productCategoryFilter->where(ProductCategoryFilter::CONDITION_FIELD_NAME_STATUS, Condition::CONDITION_EQUAL, ProductCategoryModel::STATUS_ENABLE);
		$categorysDict = $this->getAll($productCategoryFilter);
        $categorysArr = array();
        if($categorysDict){
			foreach($categorysDict as  $key=>$categoryModel){
				$categorysArr[$categoryModel->Id] = $categoryModel->toArray();
			}
		}
		if($categorysArr){
			$this->setCache(self::$cacheCategoryDictName, serialize($categorysArr));
		}
		if($return){
			return $categorysArr;
		}
	}
	
	/**
	 * 通过分类id查找
	 */
	public function getCategoryById($categoryId){
		return parent::getOneById($categoryId);
	}
	
	/**
	 * @param $productCategoryFilter \haibao\ero\model\filter\product\ProductCategory
	 */
	public function getAll($productCategoryFilter){
		return parent::getAll($productCategoryFilter);
	}
	
	/**
	 * 获取当前层级最大的排序
	 */
	public function getMaxOrderByParentId($parentId){
		$max = null;
		$sql = "select max(OrderNo) as max from ProductCategory where ParentId=%s AND Status = %s";
		$result  = $this->query($sql,array(
				$parentId,\haibao\erp\model\data\product\ProductCategory::STATUS_ENABLE
				));
		
		while ($result->fetch_assoc()){
			$max = $result->getData('max');
		}
		return $max;
	}
	
	/**
	 * 添加产品分类
	 * @param \haibao\erp\model\data\product\ProductCategory $model
	 */
	public function add($productCategoryModel){
		self::beginTranscation();
		try{
			parent::add($productCategoryModel);
			
			$this->unsetCache(self::$cacheCategoryTreeName);
			$this->unsetCache(self::$cacheCategoryDictName);
			
		}catch (\Exception $e){
			$this->rollback();
			//throw $e;
		}
		$this->endTranscation();
		return $productCategoryModel->Id;
	}
	
	
	/**
	 * 保存产品分类
	 * @param \haibao\erp\model\data\product\ProductCategory $model
	 */
	public function save($model){
		$arrSet = array();
		$arrSet[ProductCategoryFilter::CONDITION_FIELD_NAME_CATEGORY_NAME] = $model->CategoryName;
		$arrSet[ProductCategoryFilter::CONDITION_FIELD_NAEM_ORDERNO] = $model->OrderNo;
		$arrSet[ProductCategoryFilter::CONDITION_FIELD_NAME_PARENTID] = $model->ParentId;
		self::beginTranscation();
		try{
			parent::updateById($model->Id, $arrSet);
			$this->unsetCache(self::$cacheCategoryTreeName);
			$this->unsetCache(self::$cacheCategoryDictName);
		
		}catch (\Exception $e){
			$this->rollback();
 			//throw $e;
 		}
		$this->endTranscation();
	}
	/**
	 * 删除分类
	 * @param $categoryId
	 */
	public function delete($categoryId){
		self::beginTranscation();
		try{
			parent::updateById($categoryId, array('Status'=>\haibao\erp\model\data\product\ProductCategory::STATUS_DISABLE));
			$this->unsetCache(self::$cacheCategoryTreeName);
			$this->unsetCache(self::$cacheCategoryDictName);
			
		}catch (\Exception $e){
			$this->rollback();
			//throw $e;
		}
		$this->endTranscation();
	}
	/**
	 * 查找所有孩子节点
	 */
	public function getAllChildrenCategory($categoryId,$categoryAllDict = null){
		static $childArr = array();
		if(!$categoryAllDict){
			$categoryAllDict = $this->getAllCategorysDict();
		}
		foreach($categoryAllDict as $key=>$dict){
			if($dict[ProductCategoryFilter::CONDITION_FIELD_NAME_PARENTID] == $categoryId){
				array_push($childArr, $dict);
				$childArr = $this->getAllChildrenCategory($dict[ProductCategoryFilter::CONDITION_FIELD_NAME_ID] ,$categoryAllDict);
			}
		}
		return $childArr;
	}
	
	public function getParentCategoryId($categoryId){
		$parentCategoryId = 0;
		$categoryAllDict = $this->getAllCategorysDict();
		foreach($categoryAllDict as $key=>$dict){
			if($dict[ProductCategoryFilter::CONDITION_FIELD_NAME_ID] == $categoryId){
				$parentCategoryId = $dict[ProductCategoryFilter::CONDITION_FIELD_NAME_PARENTID];
				break;
			}
		}
		return $parentCategoryId;
	}
	
	/**
	 * 查询下级分类
	 * @param int $parentId
	 */
	public function getChildCategory($parentId){
		$childArr = array();
		$categoryAllDict = $this->getAllCategorysDict();
		foreach($categoryAllDict as $key=>$dict){
			if($dict[ProductCategoryFilter::CONDITION_FIELD_NAME_PARENTID] == $parentId){
				array_push($childArr, $dict);
			}
		}
		return $childArr;
	}
	
	/**
	 * \haibao\erp\model\filter\product\ProductCategoryFilter $categoryFilter;
	 */
	public function getCategoryByFilter($categoryFilter){
		return parent::getAll($categoryFilter);
	}
	
	
}
